﻿using System;
using System.IO;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using Microsoft.VisualStudio.CodeCoverage;

namespace Reporting
{
    public class ConvertCoverage : Task
    {

        [Required]
        public string CoverageFile { get; set; }

        public string SymbolsDirectory { get; set; }

        [Required]
        public string OutputFile { get; set; }

        public override bool Execute()
        {

            try
            {
                if (File.Exists(CoverageFile))
                {
                    Log.LogMessage(MessageImportance.Normal, "Converting VS Coverage File: {0}", CoverageFile);

                    string symbolsDir = Path.GetDirectoryName(CoverageFile);

                    if (SymbolsDirectory != null)
                    {
                        symbolsDir = SymbolsDirectory;
                    }

                    CoverageInfoManager.SymPath = symbolsDir;
                    CoverageInfoManager.ExePath = symbolsDir;
                    CoverageInfo info = CoverageInfoManager.CreateInfoFromFile(CoverageFile);
                    CoverageDS dataSet = info.BuildDataSet(null);

                    dataSet.WriteXml(OutputFile);

                    Log.LogMessage(MessageImportance.Normal, "Written Xml Coverage File: {0}", OutputFile);

                }
                else
                {
                    Log.LogError("Non Existent Coverage File: {0}", CoverageFile);
                }
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e);
            }

            return !Log.HasLoggedErrors;
        }


    }
}
